package Monopol;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import Cards.Card;
import Cards.Money_card;
import Cards.Move_card;
import Cards.Card.CardType;
import Cards.Move_card.eGoTo;

import GameServer.ServerService;
import Monopol.MonopolExceptions.InsufficientFunds;
import Monopol.MonopolExceptions.MonopolErrors;
import Monopol.AssetGroups.AllServices;
import Monopol.AssetGroups.AllTransportations;
import Monopol.AssetGroups.State;
import Player.Computer;
import Player.Human;
import Player.Player;
import Square.City;
import Square.Negotiable;
import Square.Square;
import Square.Square.fixedSquares;
import Utils.LoadInfo;
import Utils.Utils;

import XMLParser.MonopolyXML;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author Avia Tam
 * @author Assaf Miron
 * 
 */
public class Monopol {

    private static ArrayList<Player> players; // A List of all the Players in
    // the Game
    public static Square[] squares; // A List of the Squares in the Game
    private static ArrayList<Card> warning_cards; // A List of all the Warning
    // Cards
    private static ArrayList<Card> surprise_cards; // A List of all Surprise
    // Cards
    private static AllServices services; // A Group of All Services
    private static AllTransportations transportations; // A Group of All
    // Transportations
    private static State[] states; // A Group of All the States
    private static Double cashier; // The Total Amount of the Cashier Money
    public static Card saved_card; // Saves get out of prison card
    private static Boolean turn_over = false; // Determines if turn is over or
    // not
    public static Boolean rollDice = false; // verify if human Player wants to
    // throw the dice
    // Define Constants
    public static final int MIN_NUMBER_OF_PLAYERS = 2;
    public static final int MAX_NUMBER_OF_PLAYERS = 6;
    private Boolean autoDice;
    private Integer playerID;
    private static final int JSON_VERSION = 1;

    public Monopol() {
	// Set the Default Amount in the Cashier
	cashier = new Double(100000); // Set to 100K Shekels
    }

    public Double getCashier() {
	return cashier;
    }

    public void setCashier(Double newCash) {
	cashier += newCash;
    }

    /**
     * This Function will Clear all the Assets of this Player from there owner
     * and Delete the Player from the Players Array
     *
     * @param deleted_player
     *            The Player to be Deleted
     * @return The Player is Ready for Deletion
     */
    public static Boolean deletePlayer(Player deleted_player)
	    throws MonopolErrors {
	try {
	    // Verify that the Deleted Player is a Human
	    if (deleted_player.isHuman()) // End turn of Player
	    {
		setTurn_over(true);
	    }
	    // Delete the Players Assets
	    deleted_player.deleteAssets();
	    // Return the Players' Remaining Money back to the Cashier
	    cashier += deleted_player.getFunds();
	    // Verify that the Player has no more Assetes
	    if (deleted_player.getAssets().isEmpty()) {
//		players.remove(deleted_player);
		deleted_player.setToDelete(true);
		// Return Ready to Delete
		return true;

	    } else // Could not delete all the Players Assets
	    {
		Utils.writeText("Deleting Player Error!\n",
			deleted_player.toString());
		throw new MonopolErrors("Not All the Assets could be Cleared");
	    }
	} catch (Error e) {
	    // This Should never happen
	    throw new MonopolErrors("Something Terrible just Happened...\n"
		    + e.toString());
	}
    }

    /**
     * Buys an Asset from the Game, Sets the Player as the Owner of this Asset
     *
     * @param asset
     *            The asset to Buy
     * @param Player
     *            The Owning Player
     */
    public void buyAsset(Negotiable asset, Player player) {
	try {
	    // Buy the Asset
	    asset.buy(player);
	    // Add the Asset to the Asset List of the Player
	    player.buyAsset(asset);
	    // Inform that the User Bought this Asset
	    Utils.writeText(player.getName(), "Just Bought", asset.getName());
	} catch (InsufficientFunds trap) {
	    if (player.isHuman()) // Printout problem only if Player is human
	    {
		Utils.showError(null, trap.getMessage());
	    }
	}
    }

    /**
     * Buys a House in the City, Adds a House to where the Player is
     *
     * @param city
     *            The City where the House was built
     * @param Player
     *            The Players who built the House and owns the City
     */
    public void buyHouse(City city, Player player) {
	// Buy a House
	try {
	    // Buy a House in the City
	    city.buyHouse(player);
	    // Inform other user for this buy
	    Utils.writeText(player.getName(), "Bought a House in",
		    city.getName(), "\nTotal number of houses in",
		    city.getName(), "is", city.getNum_of_houses().toString()
		    + ".");
	} catch (InsufficientFunds trap) {
	    // Print Error to Screen
	    Utils.writeText("You don't have enough money to buy a house now.");
	}
    }

    /**
     * Helper function to Get the Square Object by a Square ID
     *
     * @param assetSquareID
     *            The Square ID on the Board
     * @return The Square Object
     */
    public Negotiable getAsset(Integer assetSquareID) {
	// Verify that the Square is an Asset
	if (squares[assetSquareID].isAsset()) {
	    // Return the Square Object
	    return squares[assetSquareID];
	} else {
	    // Not an Asset - Return Null
	    return null;
	}
    }

    /**
     * Moves the Player in the Game To the New Location
     *
     * @param Player
     *            The Player to Move
     * @param newLocation
     *            The New Location on the Board
     */
    public void movePlayer(Player player, Integer newLocation) {
	if (player.getIs_parking() == false
		&& player.getIs_in_prison() == false && !player.getToDelete()) {
	    // Move the Player to the Next Square in the Game
	    player.setGame_location(newLocation);
	} else {
	    String where = "";
	    if (player.getIs_in_prison()) {
		where = "Prison";
	    } else if (player.getIs_parking()) {
		where = "Parking";
	    } else if (player.getToDelete()) {
		where = "The Trash...";
	    }
	    Utils.writeText("Player can not Move because it is in", where);
	}
    }

    /**
     * Finds a Player by Name in the Players Array
     *
     * @param playerName
     *            The Player Name to Find
     * @return The Player Object as {@link Player}
     */
    public Player findPlayer(String playerName) {
	if (playerName != null) {
	    Iterator<Player> iterator = players.iterator();
	    while (iterator.hasNext()) {
		Player chkPlayer = ((Player) iterator.next());
		if (chkPlayer.getName().equals(playerName)) {
		    return chkPlayer;
		}
	    }
	}
	return null;
    }

    /**
     * This Function Initializes the Cards and Squares And sets each Player in a
     * position to start the Game
     */
    public void initGame(String serverName, Integer serverPort) {

	// Initialize the Players Array
	players = new ArrayList<Player>();
	// Clear the New Array List - Make sure it is empty
	players.clear();
	ServerService.getInstance().setServerName(serverName, serverPort);
    }

    /**
     * This Function will Initialize the Squares in the Game
     * From the Servers XML File. If no XML File Exists on the Server
     * Or the server returned an error on hte XML Parsing,
     * This Function will create its own Predefiened Squares
     */
    public void initSquares() {
	try {
	    // We Assume that the XSD will not change and we will always use the
	    // Same XSD
	    MonopolyXML monopolyParser = new MonopolyXML(ServerService.getInstance().getGameBoardXML());
	    // Check if the Parsing was OK
	    if (monopolyParser.getParseOK()) {
		// Get the Warning Cards Deck
		warning_cards = monopolyParser.getWarningDeck();
		// Shuffle the Cards
		Collections.shuffle(warning_cards);
		// Get the Surprise Cards Deck
		surprise_cards = monopolyParser.getSurpriseDeck();
		// Shuffle the Cards
		Collections.shuffle(surprise_cards);
		// Get all the Transportations
		transportations = monopolyParser.getAllTransportaions();
		// Get all the Services
		services = monopolyParser.getAllServices();
		// Get the Squares Order
		squares = monopolyParser.getSquaresOrder();
	    } // The Parsing got an Error - Initialize Manually
	    else {
		// Initialize the Game Squares
		squares = new Square[36]; // Set the Number of Squares
		transportations = new AllTransportations(); // Create the
		// Transportation
		// Group
		services = new AllServices(); // Create the Services Group
		// Create the Squares
		squares[fixedSquares.START_SQUARE.get()] = new Square("Start");
		Double[] stay_price = Utils.createDoubleArray((double) 20,
			(double) 30, (double) 40, (double) 80);
		states = new State[9];
		states[0] = new State("Israel", Color.pink);
		squares[1] = states[0].CreateCity("Eilat", stay_price,
			new Double(100), new Double(75));
		stay_price = Utils.createDoubleArray((double) 30,
			(double) 40, (double) 60, (double) 70);
		squares[2] = states[0].CreateCity("Kfar Saba", stay_price,
			new Double(90), new Double(100));
		squares[3] = new Square("Surprise");
		states[1] = new State("Brazil", Color.blue);
		Double[] trans_stay_price = Utils.createDoubleArray(
			(double) 50, (double) 50);
		squares[4] = transportations.createTransportation("Airline",
			trans_stay_price, new Double(100));
		stay_price = Utils.createDoubleArray((double) 250,
			(double) 300, (double) 350, (double) 400);
		squares[5] = states[0].CreateCity("Tel Aviv", stay_price,
			new Double(550), new Double(100));
		stay_price = Utils.createDoubleArray((double) 20,
			(double) 30, (double) 40, (double) 80);
		squares[6] = states[1].CreateCity("Brazilia", stay_price,
			new Double(100), new Double(75));
		;
		stay_price = Utils.createDoubleArray((double) 30,
			(double) 40, (double) 60, (double) 70);
		squares[7] = states[1].CreateCity("Rio De Janeiro", stay_price,
			new Double(90), new Double(100));
		squares[8] = new Square("Warning");
		squares[fixedSquares.PRISON_SQUARE.get()] = new Square("Prison");
		states[2] = new State("Canada", Color.yellow);
		squares[10] = states[1].CreateCity("Sao Paulo", stay_price,
			new Double(110), new Double(100));
		stay_price = Utils.createDoubleArray((double) 250,
			(double) 300, (double) 350, (double) 400);
		squares[11] = states[2].CreateCity("Montreal", stay_price,
			new Double(300), new Double(100));
		squares[12] = states[2].CreateCity("Toronto", stay_price,
			new Double(400), new Double(50));
		Double[] service_stay_price = Utils.createDoubleArray(
			(double) 50, (double) 50);
		squares[13] = services.createService("Internet",
			service_stay_price, new Double(100));
		service_stay_price = Utils.createDoubleArray(
			(double) 20, (double) 20);
		squares[14] = transportations.createTransportation("Train",
			trans_stay_price, new Double(50));
		states[3] = new State("England", Color.black);
		squares[15] = states[3].CreateCity("London", stay_price,
			new Double(600), new Double(100));
		squares[16] = states[3].CreateCity("Machester", stay_price,
			new Double(350), new Double(25));
		squares[17] = states[3].CreateCity("Liverpool", stay_price,
			new Double(300), new Double(15));
		squares[fixedSquares.PARKING_SQUARE.get()] = new Square(
			"Parking");
		states[4] = new State("Spain", Color.green);
		squares[19] = states[4].CreateCity("Madrid", stay_price,
			new Double(550), new Double(75));
		squares[20] = states[4].CreateCity("Valencia", stay_price,
			new Double(350), new Double(20));
		squares[21] = states[4].CreateCity("Barcelona", stay_price,
			new Double(500), new Double(80));
		squares[22] = new Square("Warning");
		trans_stay_price = Utils.createDoubleArray(
			(double) 10, (double) 10);
		squares[23] = transportations.createTransportation("Egged",
			trans_stay_price, new Double(100));
		states[5] = new State("Germany", Color.red);
		squares[24] = states[5].CreateCity("Berlin", stay_price,
			new Double(550), new Double(75));
		squares[25] = states[5].CreateCity("Munich", stay_price,
			new Double(350), new Double(20));
		squares[26] = states[5].CreateCity("Hamburg", stay_price,
			new Double(500), new Double(80));
		squares[fixedSquares.GO2PRISON_SQUARE.get()] = new Square(
			"Go to Prison");
		states[6] = new State("USA", Color.cyan);
		squares[28] = states[6].CreateCity("New york", stay_price,
			new Double(610), new Double(100));
		squares[29] = states[6].CreateCity("Chicago", stay_price,
			new Double(500), new Double(90));
		squares[30] = states[6].CreateCity("Los angeles", stay_price,
			new Double(570), new Double(95));
		states[7] = new State("Italy", Color.magenta);
		squares[31] = services.createService("Electricity",
			service_stay_price, new Double(50));
		squares[32] = transportations.createTransportation("Metro",
			trans_stay_price, new Double(100));
		squares[33] = states[7].CreateCity("Milan", stay_price,
			new Double(550), new Double(75));
		squares[34] = states[7].CreateCity("Roma", stay_price,
			new Double(500), new Double(80));
		states[8] = new State("Vatican", Color.lightGray);
		stay_price = Utils.createDoubleArray((double) 100,
			(double) 150, (double) 300, (double) 450);
		squares[35] = states[8].CreateCity("Vatican City", stay_price,
			new Double(1000), new Double(1500));


//		// Initializing the Cards
//		// 3 types of warning Cards 1.go to prison ,2.go to next warning
//		// Square ,3.pay
//		warning_cards = new ArrayList<Card>();
//		warning_cards.add(new Move_card(CardType.WARNING_CARD,
//			"Go to prison", eGoTo.PRISON));
//		warning_cards.add(new Move_card(CardType.WARNING_CARD,
//			"Go to prison", eGoTo.PRISON));
//		warning_cards.add(new Move_card(CardType.WARNING_CARD,
//			"Go to prison", eGoTo.PRISON));
//		warning_cards.add(new Move_card(CardType.WARNING_CARD,
//			"Go to next warning Square", eGoTo.NEXT_WARNING));
//		warning_cards.add(new Move_card(CardType.WARNING_CARD,
//			"Go to next warning Square", eGoTo.NEXT_WARNING));
//		warning_cards.add(new Move_card(CardType.WARNING_CARD,
//			"Go to next warning Square", eGoTo.NEXT_WARNING));// need
//		// to
//		// edit
//		// move
//		// card
//		warning_cards.add(new Money_card(CardType.WARNING_CARD,
//			"Pay 500 to Cashire", new Double(100), true));
//		warning_cards.add(new Money_card(CardType.WARNING_CARD,
//			"Pay 700 to Players", new Double(70), false));
//		warning_cards.add(new Money_card(CardType.WARNING_CARD,
//			"Pay 100 to Players", new Double(10), false));// trick
//		// card
//		// doesn't
//		// do as
//		// tells
//		// Shuffle the Cards
//		Collections.shuffle(warning_cards);
//		// 4 types of surprise_cards 1.go to start,2.go to next surprise
//		// Square,3.get money 4.get out of prison
//		surprise_cards = new ArrayList<Card>();
//		surprise_cards.add(new Card(CardType.SURPRISE_CARD,
//			"Get out of prison"));
//		surprise_cards.add(new Move_card(CardType.SURPRISE_CARD,
//			"Go to start", eGoTo.START));
//		surprise_cards.add(new Move_card(CardType.SURPRISE_CARD,
//			"Go to start", eGoTo.START));
//		surprise_cards.add(new Move_card(CardType.SURPRISE_CARD,
//			"Go to next surprise Square", eGoTo.NEXT_SURPRISE));
//		surprise_cards.add(new Move_card(CardType.SURPRISE_CARD,
//			"Go to next surprise Square", eGoTo.NEXT_SURPRISE));
//		surprise_cards.add(new Move_card(CardType.SURPRISE_CARD,
//			"Go to next surprise Square", eGoTo.NEXT_SURPRISE));
//		surprise_cards.add(new Money_card(CardType.SURPRISE_CARD,
//			"Get 500", new Double(500), true));
//		surprise_cards.add(new Money_card(CardType.SURPRISE_CARD,
//			"Get 700 from players", new Double(70), false));
//		surprise_cards.add(new Money_card(CardType.SURPRISE_CARD,
//			"Get 100 from players", new Double(10), false));// trick
//		// card
//		// doesn't
//		// do as
//		// tells
//		// Shuffle the Cards
//		Collections.shuffle(surprise_cards);
	    }
	} catch (Exception e) {
	    Logger.getLogger(Monopol.class.getName()).log(Level.SEVERE, null, e);
	    System.out.println("The Server is not Avialable");

	    // Critical Error - Exit the Game
	    System.exit(1);
	}
    }

    /**
     * Updates the Players Array in the Game
     * @param gameName
     *	The Game Nameas it appears in the Server
     * @param totalNumOfPlayers
     *	The Total Number of Players in the Game
     * @return
     *	The Number of Players Added to the Array
     */
    public Integer updatePlayers(String gameName, Integer totalNumOfPlayers) {
	// Get the Players Array that was Created in the Loading Window
	LoadInfo[] arrPlayers = new LoadInfo[totalNumOfPlayers];
	// Get All the Players in the Game from the Server
	ServerService.getInstance().getPlayersDetails(gameName).toArray(arrPlayers);
	// Loop the Players Information in the Array
	Integer counter = 0; // insert player index
	// Clear the Players Array - will re-create now
	players.clear();
	for (LoadInfo playerInfo : arrPlayers) {
	    if (playerInfo != null) {
		// Check Each Player and Create the Players
		if (playerInfo.getIsHuman()) {
		    // Create a new Human Player
		    Human player = new Human(playerInfo.getPlayerName(),
			    playerInfo.getInitFunds(),
			    playerInfo.getPlayerColor(), counter);
		    // Add the New Player to the Game
		    players.add(player);
		} else {
		    // Create a new Computer Player
		    Computer player = new Computer(playerInfo.getPlayerName(),
			    playerInfo.getInitFunds(),
			    playerInfo.getPlayerColor(), counter);
		    // Add the New Player to the Game
		    players.add(player);
		}
		counter++;// increment player index
	    }
	}
	return counter;
    }

    /**
     * This Function Loads the Monopoly Players
     */
    public Boolean loadGame(String gameName, Integer humans, Integer computers,
	    Boolean isAutoDice) {
	// Check the Automatic Dice Roll Mode in the Game
	this.autoDice = isAutoDice;
	// Set the Total number of players in the game
	Integer totalNumOfPlayers = humans + computers;

	// Checks and Returns the Load Game Status
	if (updatePlayers(gameName, totalNumOfPlayers) > 0) {
	    return true;
	} else {
	    return false;
	}
    }

    public Integer getPlayerID() {
	return playerID;
    }

    /**
     * Getter function for the Game Squares If no Squares are loaded when this
     * Function is Called, The {@link initGame()} Function is Called
     *
     * @return The Game Squares Array
     */
    public Square[] getGameSquares() {
	if (squares == null) {
	    // This should Never Happen...
	    // In case of No initialization - Revert to Defaults
	    initGame("localhost", 8080);
	}
	return squares;
    }

    /**
     * A Getter for the Game Players.
     *
     * @return The Game Players Array List
     * @throws Monopol.MonopolExceptions.MonopolErrors
     *             On Errors
     */
    public ArrayList<Player> getPlayers() throws MonopolErrors {
	if (players == null) {
	    throw new MonopolErrors("No Players in the Game!");
	}
	return players;
    }

    /**
     * Returns the Square Name of the Players Location
     *
     * @param location
     *            The Current Player Location
     * @return The Name of the Square the Player is at
     */
    public static String getSquareName(Integer location) {
	return squares[location].getName();
    }

    /**
     * Returns the Game Squares Object
     * @return
     *	The Game Squares Object
     */
    public Square[] getSquares() {
	if (squares != null) {
	    return squares;
	} else {
	    Square[] emptySquare = new Square[0];
	    return emptySquare;
	}
    }

    /**
     * Check if a Player passed the Start Square and does it need to get paid
     *
     * @param prevLocation
     *            The Previous Player Location
     * @param currLocation
     *            The Current Player Location
     * @return The Amount the Game Needs to Play the Player
     */
    public Double checkGo2Start(Integer prevLocation, Integer currLocation,
	    String player_name) {
	if (cashier > 0) {
	    // Check if The Player went pass the Start Square
	    if (prevLocation > currLocation) {
		// Check if the Player is ON the Start Square
		if (currLocation == 0) {
		    // Inform that the Player got 400 Shekels
		    Utils.writeText(player_name,
			    "Got to the Start Square and Recieved 400 Shekels!");
		    // Reduce 400 Shekels from the Cashier
		    cashier -= 400;

		    // Return the Player 400 Shekels for Standing on the Start
		    // Square
		    return 400.0;
		} else {
		    // Inform that the Player got 200 Shekels
		    Utils.writeText(player_name, "Recieved 200 Shekels!");
		    // Reduce 200 Shekels from the Cashier
		    cashier -= 200;

		    // Return the Player 200 Shekels for Passing the Start
		    // Square
		    return 200.0;
		}
	    } else // Player did not pass the Start Square
	    {
		return 0.0;
	    }
	} else // No Money in the Cashier
	{
	    Utils.writeText("Sorry but there is no money left in the Bank...");
	}
	return 0.0;

    }

    public Boolean getTurn_over() {
	return turn_over;
    }

    public static void setTurn_over(Boolean turn_over) {
	Monopol.turn_over = turn_over;
    }

    public static void SetRolldice(Boolean rollDice) {
	Monopol.rollDice = rollDice;

    }

    public static Boolean getRolldice() {
	return rollDice;
    }

    /**
     * Returns the Dice Mode: Automatic Dice Roll or Manual Dice Roll
     *
     * @return
     *	    The Dice Mode
     */
    public Boolean getAutomaticDiceMode() {
	return autoDice;
    }

    /**
     * Creates the Players JSON Object
     * Contians the Position and State of Every Playing Player in the Game
     * @return
     *	    A JSON Array of All Playing Players State
     */
    private JSONArray playersJSONBuilder() {
	JSONArray jplayers = new JSONArray();// General JSON players array
	JSONArray jassets = new JSONArray();// General JSON players array
	NumberFormat formatter = NumberFormat.getCurrencyInstance();
	// Create the JSON Players Array
	for (Player player : players) {// move all players to array
	    // Clear the Assets Count
	    jassets.clear();
	    if (!player.getToDelete())// if player was not deleted
	    {
		JSONObject newplayer = new JSONObject();// creating a new JSON
		// for each player
		newplayer.put("id", new Integer(players.indexOf(player)) + 1);
		newplayer.put("name", player.getName());
		newplayer.put("location", player.getGame_location() + 1);
		newplayer.put("funds", formatter.format(player.getFunds()));
		for (Square asset : player.getAssets()) {// for each asset
		    // create new JSON
		    // object
		    JSONObject newasset = new JSONObject();// create object for
		    // each asset
		    Integer index;// index of square in the game
		    index = findSquare(asset);
		    newasset.put("name", getSquareName(index));
		    newasset.put("address", index + 1);// input index place
		    if (asset.isCity()) {
			Integer numOfHouses;// number of houses on City
			numOfHouses = ((City) asset).getNum_of_houses();
			newasset.put("houses", numOfHouses);
		    }
		    jassets.add(newasset);// add new asset to array
		}
		newplayer.put("assets", jassets);//asigning assets to player
		// Check if Player has a Get Out of Prinson Card
		if(player.getRelease_from_prison_card()){
		    newplayer.put("prisoncard", player.getRelease_from_prison_card());
		}
		jplayers.add(newplayer);// add the new player to the array
	    }// end of if
	}// end of for
	return jplayers;
    }

    /**
     * Creates an Automatic Cube throw JSON Object
     * @param cube1
     *	    The First Cube Value
     * @param cube2
     *	    The Second Cube Value
     */
    public JSONObject cubesStatusBuilder(Integer cube1, Integer cube2) {
	System.out.println("new Auto-Cubes json is created");
	JSONObject json = new JSONObject();// general object
	JSONObject jCubes = new JSONObject(); // Genreal JSON Cubes Object

	// Create the JSON Cubes Array
	jCubes.put("cube1", cube1);
	jCubes.put("cube2", cube2);

	json.put("ver", JSON_VERSION);// create version identifier
	json.put("players", playersJSONBuilder());// add all players
	json.put("cubes", jCubes); // Add the Cubes Array
	// store new JSON
	return json;
    }

    /**
     * Creates a Notification JSON Message for the Player
     * @param messageNotifier
     *		The Message to display
     */
    public void notificationStatusBuilder(String messageNotifier, Integer dice1, Integer dice2) {
	System.out.println("new Notifier json is created");
	JSONObject json = new JSONObject();// general object
	JSONObject jspec = new JSONObject();// general object
	json = cubesStatusBuilder(dice1, dice2);
	if (!messageNotifier.isEmpty())// if notification appeared please
	{
	    JSONObject cont = new JSONObject();// message constant
	    cont.put("message", messageNotifier);// insert question
	    json.put("notification", cont);
	}

	// store new JSON
	setJSONObjects(json);
    }

    /**
     * Creates a JSON for a Dice throw Dialog
     * @param dicesDialog
     *	Displaay this Dice Dialog
     * @param dialogID
     *	The Dialog ID
     * @param i_playerName
     *	The Player ID to Display the dialog to
     */
    public void diceDialogBuilder(Boolean dicesDialog, Integer dialogID, String i_playerName, Integer dice1,
	    Integer dice2) {
	System.out.println("new Dices Dialog json is created");
	JSONObject json = new JSONObject();// general object
	JSONObject jspec = new JSONObject();// general object
	json = cubesStatusBuilder(dice1, dice2);
	if (dicesDialog)// if dices are manually entered
	{
	    jspec.put("id", dialogID); // Insert the Dialog ID
	    jspec.put("playerName", i_playerName);// insert player ID
	    jspec.put("dices", true);
	}
	json.put("dicesDialog", jspec);
	// store new JSON
	setJSONObjects(json);
    }

    /**
     * Creates a JSON for a prompt (asset / house) Dialog
     * @param promptQuestion
     *	The Question text to display to the player
     * @param dialogID
     *	The Dialog ID
     * @param i_playerName
     *	The Player ID to Display the dialog to
     */
    public void promptDialogBuilder(String promptQuestion, String promptDetails, String assetState, Integer dialogID, String i_playerName, Integer dice1, Integer dice2) {
	System.out.println("new Prompt Dialog json is created");
	JSONObject json = new JSONObject();// general object
	JSONObject jDialog = new JSONObject(); //Dialog JSON Object
	json = cubesStatusBuilder(dice1, dice2);
	// if a dialog is prompt to user
	if (!promptQuestion.isEmpty()) {
	    if (dialogID == MonopolyGame.BUY_ASSET_DIALOG_ID) {
		jDialog.put("id", "asset"); // Insert the Dialog ID
	    } else if (dialogID == MonopolyGame.BUY_HOUSE_DIALOG_ID) {
		jDialog.put("id", "house"); // Insert the Dialog ID
	    } else {
		jDialog.put("id", dialogID); // Insert the Dialog ID
	    }

	    jDialog.put("playerName", i_playerName);// insert player ID
	    jDialog.put("question", promptQuestion);// insert question
	    jDialog.put("details", promptDetails); // Insert the Details for this Dialog
	    jDialog.put("state", assetState); // Insert the Asset Group State
	    jDialog.put("option1", "Yes");// insert options to answer
	    jDialog.put("option2", "No, thank you");
	}
	// Put the Array in the JSON Special Object
	json.put("questDialog", jDialog);
	// store new JSON
	setJSONObjects(json);
    }

    /**
     * Sets the JSON Objects in there Servet Array
     * Used mainly for debugging
     * @param i_oJSON
     *	    The JSON object containing all Basic JSON Data
     * @param i_oJSONDialogs
     *	    The JSON Object containing any Special Data
     */
    private void setJSONObjects(JSONObject i_oJSON) {
	NumberFormat formatter = NumberFormat.getCurrencyInstance();
	// Add the Cashier Value to the JSON
	i_oJSON.put("cashier", formatter.format(cashier));
	monopolyServlet.MonopolyServlet.JsonUpdate(i_oJSON);
	System.out.println("DEBUG:");
	System.out.println(i_oJSON);
	System.out.println("event was converted to JSON");
    }

    // used to find a square in the array and return index , called in
    // jsonbuilder
    static private Integer findSquare(Square asset) {
	Integer index = 0;
	for (int i = 0; i < squares.length; i++) {
	    if (squares[i].equals(asset)) {
		index = i;
		i = squares.length;
	    }
	}
	return index;// return index
    }
}
